package test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.sql.DataSource;
@Stateful
public class Account implements AccountRemote, AccountLocal {
    @Resource(name = "sample")
    private DataSource sample;
    Connection conn;
    double account=-1.0;
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    public Account() {
    }
    @Override
    public void depoist(double amount) throws Exception{
        if(amount<0)throw new Exception("Invalid amount");
        account+=amount;
    }
    @Override
    public void withdraw(double amount) throws Exception{
        if(amount<0)throw new Exception("Invalid amount");
        if(account<amount) throw new Exception("not enough money");
        account-=amount;
    }
    @Override
    public double getBalance(String id) throws Exception{
        if(account<0)
        {
            if(conn!=null){
            String sql="select amount from account where id= "+id;
            try{
                Statement s=conn.createStatement();
                ResultSet re= s.executeQuery(sql);
                if(re.next())account=re.getInt("amount");
            }catch(Exception e){
                System.out.println(e.toString());
            }
            }
        }
        return account;
    }
    @PostConstruct
    @PostActivate
    public void openConnection()
    {
        try {
            conn=sample.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(Account.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    @PrePassivate
    @PreDestroy
    public void cleanup()
    {
        try {
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(Account.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    @Remove
    public void updateAccount(String id)
    {
        if(conn!=null){
        String sql="update account set amount =? where id= "+id;
        try{
                PreparedStatement s=conn.prepareStatement(sql);
                s.setDouble(1, account);
                int re= s.executeUpdate();
            }catch(Exception e){
                System.out.println(e.toString());
            }
        }
    }
}
